<?php
require_once 'setup.inc.php';

if ($config['Use Teamspeak']) {
  $ts_server = connect_ts() or log_message('Error connecting to TS server when running check script.');

  //Get list of TS UIDs of currently connected clients
  foreach ($ts_server->clientList() as $client) {
    $uid = $client->getProperty('client_unique_identifier');
    if ($uid != 'serveradmin') {
      $ts_clients[] = $uid;
    }
  }
  if (empty($ts_clients)) {
    $ts_clients = 'NULL';
  }
  else {
    $ts_clients = '"' . implode('",' . "\n" . '"', $ts_clients) . '"';
  }
}

connect_forums_db();

//Get forums user info checked longest ago
if ($config['Use Teamspeak']) {
  $query = <<<EOL
SELECT 
  User AS ID,
  `Key ID`,
  `Key Ver Code`,
  `TS UID`,
  `TS UID` IN ({$ts_clients}) AS `In TS`,
  username AS Username
FROM `EVE Registration`
JOIN {$config['Forums DB']['Table Prefix']}users ON {$config['Forums DB']['Table Prefix']}users.user_id = `EVE Registration`.User
WHERE `Cached Until` IS NULL
OR `Cached Until` < DATE_SUB(NOW(), INTERVAL {$config['Check Frequency']['Not In TS']} HOUR)
OR (
  `TS UID` IN ({$ts_clients})
  AND
  `Cached Until` < DATE_SUB(NOW(), INTERVAL {$config['Check Frequency']['In TS']} HOUR)
)
ORDER BY `In TS` DESC, `Cached Until`, ID DESC
LIMIT 1
EOL;
}
else {
  $query = <<<EOL
SELECT 
  User AS ID,
  `Key ID`,
  `Key Ver Code`,
  username AS Username
FROM `EVE Registration`
JOIN {$config['Forums DB']['Table Prefix']}users ON {$config['Forums DB']['Table Prefix']}users.user_id = `EVE Registration`.User
WHERE `Cached Until` IS NULL
OR `Cached Until` < DATE_SUB(NOW(), INTERVAL {$config['Check Frequency']['Not In TS']} HOUR)
ORDER BY `Cached Until`, ID DESC
LIMIT 1
EOL;
}
$result = mysql_query($query) or log_message('Error getting forums user information.');
$forums_user = mysql_fetch_assoc($result) or die;  //Quit if nobody should be checked

//Get corporation ID and check key for potential problems
$corp = get_eve_corp($forums_user['Key ID'], $forums_user['Key Ver Code'], $forums_user['Username']);
if ($corp == -1) { //API connection error
  log_message('Error connecting to EVE API server. Not an API key problem. User: ' . $forums_user['Username']);
}
elseif ($corp !== FALSE) {
  $user['Corp ID'] = $corp[0];
  $user['Cached Until'] = $corp[1];
}
else {
  $user['Corp ID'] = FALSE;
}
if ($user['Corp ID'] !== FALSE and !array_key_exists($user['Corp ID'], $config['Corps'])) {
  log_message('Character is not in any of the configured corps. User: ' . $forums_user['Username'], FALSE);
  $user['Corp ID'] = FALSE;
}

//Delete registration if API was bad or didn't match a registered corp
if ($user['Corp ID'] === FALSE) {
  log_message('Revoking all rights and deleting API registration for user. User: ' . $forums_user['Username'], FALSE);
  $query = <<<EOL
DELETE FROM `EVE Registration`
WHERE User = "{$forums_user['ID']}"
EOL;
  mysql_query($query) or log_message('Error deleting user\'s API registration entry.');
}
else { //Update user's Cached Until timestamp
  //Since EVE is currently only caching "account/APIKeyInfo.xml.aspx" for about 5 minutes
  //  and the script shouldn't hammer their server like that, Cached Until will be set to
  //  at least an hour from this check.  I assume they'll make it an hour eventually.
  if ($user['Cached Until'] - time() < 3600) {
    $user['Cached Until'] = time() + 3600;
  }
  $query = <<<EOL
  UPDATE `EVE Registration`
  SET `Cached Until` = FROM_UNIXTIME({$user['Cached Until']})
  WHERE User = {$forums_user['ID']}
EOL;
  mysql_query($query) or log_message('Error updating user\'s Cached Until timestamp.  User: ' . $forums_user['Username']);
}

//Determine proper forums group
if ($user['Corp ID'] !== FALSE) {
  $forums_user['Group'] = $config['Corps'][$user['Corp ID']][1];
}
else {
  //If the user wasn't in a registered corp., set their assigned group as Register Users.
  // It feels odd specifying a group here, as technically the default groups can be modified, but
  // it's better than setting it to a blank value, which would in turn use the database default of
  // 3 (REGISTERED_COPPA), where 2 is REGISTERED
  $forums_user['Group'] = 2;
}

//Remove user from all forums groups except those ignored
$query = <<<EOL
DELETE
FROM {$config['Forums DB']['Table Prefix']}user_group
WHERE user_id = {$forums_user['ID']}
AND group_id NOT IN ({$config['Ignore Forums Groups']})
EOL;
mysql_query($query) or log_message('Error removing user from all forums groups. User: ' . $forums_user['Username']);

//Add user, if properly registered to a corp., to that forums group
if ($user['Corp ID'] !== FALSE) {
  $query = <<<EOL
INSERT INTO {$config['Forums DB']['Table Prefix']}user_group
(group_id, user_id, user_pending)
VALUES ({$forums_user['Group']}, {$forums_user['ID']}, 0)
EOL;
  mysql_query($query) or log_message('Error adding user to correct forums group. User: ' . $forums_user['Username']);
}

//Set user's default forums group and clear user's permission cache,
$query = <<<EOL
UPDATE {$config['Forums DB']['Table Prefix']}users
SET
  group_id = {$forums_user['Group']},
  user_permissions = ''
WHERE user_id = {$forums_user['ID']}
EOL;
mysql_query($query) or log_message('Error setting default forums group and clearing permission cache. User: ' . $forums_user['Username']);

if ($config['Use Teamspeak']) {
  //Get client's TS DB ID
  try {
    $ts_client_db_id = $ts_server->clientFindDb($forums_user['TS UID'], TRUE);
  }
  catch (Exception $exception) {
    if (strpos($exception, 'database empty result set') !== FALSE) {
      log_message('Couldn\'t find client\'s TS database ID by UID.  This means the UID is either invalid or they\'ve never connected. User: ' . $forums_user['Username'] . '. UID: ' . $forums_user['TS UID']);
    }
    log_message('An unknown exception happened while getting TS client database ID based on Unique ID. User: ' . $forums_user['Username'] . '. UID: ' . $forums_user['TS UID']);
  }

  //Get client's TS DB ID
  $ts_client_db_id = get_ts_user_db_id($ts_server, $forums_user['TS UID']) or log_message('Couldn\'t find client\'s TS database ID by UID.  This means the UID is either invalid or they\'ve never connected. User: ' . $forums_user['Username'] . '. UID: ' . $forums_user['TS UID']);
  if ($ts_client_db_id == -1) {
    die; //exception happened and was logged
  }

  //Get TS group from config. based on corp.
  if ($user['Corp ID'] === FALSE) {
    $user['TS Group'] = 0;
  }
  else {
    $user['TS Group'] = $config['Corps'][$user['Corp ID']][0];
  }

  //Remove user from all groups except the one they should be in
  $config['Ignore TS Groups'] = explode(',', $config['Ignore TS Groups']);
  $ts_groups = $ts_server->clientGetServerGroupsByDbid($ts_client_db_id);
  foreach ($ts_groups as $group) {
    if ($group['sgid'] == $user['TS Group']) {
      $in_proper_group = TRUE;
    }
    elseif (!in_array($group['sgid'], $config['Ignore TS Groups'])) {
      $ts_server->serverGroupClientDel($group['sgid'], $ts_client_db_id);
    }
  }

  //Add user to their group if they weren't in it
  if (!isset($in_proper_group) and $user['TS Group'] != 0) {
    $ts_server->serverGroupClientAdd($user['TS Group'], $ts_client_db_id);
  }
}
?>